package com.jsecode.lib.util;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class GsonUtil {

    public static final String DATE_FORMAT_DEFAULT= "yyyy-MM-dd hh:mm:ss";
    public static Gson gsonDefault = null;
    
    /** 创建/获取默认的gsonBuilder */
    public static Gson getDefaultGson() {
        if(gsonDefault == null) {
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.setDateFormat(DATE_FORMAT_DEFAULT);
            gsonDefault = gsonBuilder.create();
        }
        
        return gsonDefault;
    }
    
    /**
     * 暂时没用到的类, 可以转Timestamp格式
     * @author luodan
     *
     */
    public static class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp>{  
        private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      
        @Override
        public Timestamp deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2) throws JsonParseException{
            if (!(json instanceof JsonPrimitive)) {      
                throw new JsonParseException("The date should be a string value");      
            }      
         
            try {      
                Date date = format.parse(json.getAsString());      
                return new Timestamp(date.getTime());      
            } catch (ParseException e) {      
                throw new JsonParseException(e);      
            }    
        }
        @Override
        public JsonElement serialize(Timestamp ts, Type arg1, JsonSerializationContext arg2){
            String dfString = format.format(new Date(ts.getTime()));      
            return new JsonPrimitive(dfString);   
        }      
    }  
}
